package javatest.guireceiver;

import com.googlecode.javacv.cpp.opencv_core;
import com.vpx.VpxDecoder;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Arrays;
import javax.swing.JPanel;

/**
 * @author sad
 */
public class VideoShower extends JPanel {

    private final VpxDecoder decoder;
    private final opencv_core.IplImage image;
    private int counter = -1;
    private int missedFrames = 0;

    private boolean shouldAdd = false;

    public VideoShower() {
        setBackground(Color.WHITE);
        setPreferredSize(new Dimension(322, 242));
        setMinimumSize(new Dimension(322, 242));
        setOpaque(true);
        setLayout(null);
        BufferedImage ti = new BufferedImage(160, 120, BufferedImage.TYPE_3BYTE_BGR);
        image = opencv_core.IplImage.createFrom(ti);
        decoder = new VpxDecoder(image.width(), image.height());
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        if (image != null) {
            g.drawImage(image.getBufferedImage(), this.getWidth() / 2 - image.width() / 2, this.getHeight() / 2 - image.height() / 2, this);
        }
    }

    public void setShouldAdd(boolean shouldAdd) {
        this.shouldAdd = shouldAdd;
    }

    public void process(byte[] bytes, int frameCounter) {
        //if (shouldAdd) {
        //    System.out.println("" + frameCounter + " - " + bytes.length);
        //}
        if (counter == -1) {
            counter = frameCounter;
        } else {
            if (frameCounter < counter) {//skip if frame older than need
                return;
            } else {
                if ((frameCounter - counter) > 1) {
                    missedFrames += frameCounter - counter;
                    setToolTipText("" + missedFrames);
                }
            }
        }

        counter = frameCounter;
        byte[] picBytes = Arrays.copyOfRange(bytes, 7, bytes.length);
        try {
            decoder.decodeImage(image, picBytes);
        } catch (Exception ex) {
        }
        repaint();
    }
}
